//
//  WLRouterSettingVController.m
//  WanLian
//
//  Created by muzhuang on 2018/10/17.
//  Copyright © 2018年 wanlian. All rights reserved.
//

#import "WLRouterSettingVController.h"
#import "WLRouterInternetSetController.h"
#import "WLRouterWiFiSetController.h"
#import "WLRouterDeviceManagerController.h"
#import "WLRouterShareDiskController.h"
#import "WLRouterBlackDeviceController.h"
#import "WLRouterConfigModel.h"

@interface WLRouterSettingVController ()<UITableViewDelegate,UITableViewDataSource>//,RouterSocketDelegate>

@property (nonatomic, copy) NSArray *arrTitles;
@property (nonatomic, strong) UITableView *tbSetting;
@property (nonatomic, copy) NSDictionary *dictInfo;
@property (nonatomic, strong) WLRouterConfigModel *configModel;
@property (nonatomic, assign) BOOL isShowBlack;

@end

@implementation WLRouterSettingVController

- (void)dealloc
{
    [[WLSocketManager sharedSocketManager] removeDelegate:self delegateQueue:dispatch_get_main_queue()];
//    [[WLSocketManager sharedSocketManager] removeDelegate:self];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
//    [self reqRouterInfo];
//    [self reqCurrentRouterInfo];
    [self receiveRouterInformation];
}
- (void)viewDidDisappear:(BOOL)animated {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:KRouterWillDisonnected object:nil];
}
- (void)disconnected {
    
    [SVProgressHUD showAndAutoCloseWithStatus:@"失去连接" delayTime:2.f];
    [self.navigationController popToRootViewControllerAnimated:YES];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(disconnected) name:KRouterWillDisonnected object:nil];
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSInteger guideIndex = [userDefaults integerForKey:@"maskGuideIndex"];
    if (guideIndex<4)
    {
        [self showSettingMaskView];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"设置";
    
//    arrTitles =@[@[@"联网设置",@"WiFi设置"],@[@"联网设备管理",@"共享磁盘管理",@"黑名单管理"],@[@"路由器软件版本"]];
    _arrTitles =@[@[@"联网设置",@"WiFi设置"],@[@"联网设备管理",@"共享磁盘管理",@"防火墙"]];
    _tbSetting = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    _tbSetting.backgroundColor = wlUIColorRGB(0xFAFAFA);
    _tbSetting.delegate = self;
    _tbSetting.dataSource = self;
    _tbSetting.rowHeight = WLScaleX(58);
    if (@available(iOS 11.0, *)) {
        _tbSetting.estimatedSectionHeaderHeight = 0;
        _tbSetting.estimatedSectionFooterHeight = 0;
    }
    [self.view addSubview:_tbSetting];
    _tbSetting.scrollEnabled = NO;
    WLWkSelf
    [_tbSetting mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(weakSelf.view);
    }];
    
    [[WLSocketManager sharedSocketManager] addDelegate:self delegateQueue:dispatch_get_main_queue()];
//    [[WLSocketManager sharedSocketManager] addDelegate:self];
//    [self reqRouterInfo];
//    [self reqCurrentRouterInfo];
}

- (void)receiveRouterInformation
{
    NSDictionary *dict = @{@"type":@"DEVICE_LOADING_REQ",@"content":@""};
    [[WLSocketManager sharedSocketManager] sendMessage:dict timeOut:-1 tag:0];
}

#pragma mark - 接收消息代理
- (void)didReceiveMessage:(WLSocketModel *)msgModel withTag:(long)tag
{
//    if ([msgModel.type isEqualToString:@"REGISTER_SUCCESS"]) {
//
//    }
    if ([msgModel.type isEqualToString:@"DEVICE_LOADING_REP"])
    {
        if (msgModel.content != nil) {
            NSData *jsonData = [msgModel.content dataUsingEncoding:NSUTF8StringEncoding];
            NSError *err;
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                                options:NSJSONReadingMutableContainers
                                                                  error:&err];
            self.dictInfo = dic;
            _isShowBlack = [dic[@"blackStatus"] boolValue];
            if (_isShowBlack) {
                _arrTitles =@[@[@"联网设置",@"WiFi设置"],@[@"联网设备管理",@"共享磁盘管理",@"防火墙",@"黑名单管理"]];
            }
            else
            {
                _arrTitles =@[@[@"联网设置",@"WiFi设置"],@[@"联网设备管理",@"共享磁盘管理",@"防火墙"]];
            }
            [self.tbSetting reloadData];
        }
    }
    else if ([msgModel.type isEqualToString:@"COMMON_SUCCESS"])
    {
        
    } else if ([msgModel.type isEqualToString:@"COMMON_DEVICE_KEY_ERROR"]) {
        [self disconnected];
    }
}

- (void)reqRouterInfo
{
    WLWkSelf
    [WLHttpManager WLRequestMethod:RequestTypePost urlStr:@"device/get/setinfo" withParamsDic:nil success:^(NSDictionary *successDict) {
        weakSelf.dictInfo = successDict[@"object"];
        [weakSelf.tbSetting reloadData];
    } failure:^(NSString *errorMsg, NSInteger errorTag) {
        [weakSelf showHUDMessage:errorMsg];
    } error:^(NSError *error) {
        
    } inView:self.view];
}

- (void)reqCurrentRouterInfo
{
    WLWkSelf
    [WLHttpManager WLRequestMethod:RequestTypePost urlStr:@"device/app/info" withParamsDic:nil success:^(NSDictionary *successDict) {
        NSDictionary *dictRet = successDict[@"object"];
        weakSelf.configModel = [WLRouterConfigModel mj_objectWithKeyValues:dictRet[@"deviceConfig"]];
    } failure:^(NSString *errorMsg, NSInteger errorTag) {
//        [weakSelf showHUDMessage:errorMsg];
    } error:^(NSError *error) {
        
    } inView:nil];
}

#pragma mark - UITableView
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return _arrTitles.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return WLScaleX(10);
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [_arrTitles[section] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger row = indexPath.row;
    static NSString *strSetting = @"settingCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:strSetting];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:strSetting];
        cell.textLabel.font = [WLCommonTool fontTypePingFangSCRegular:17];
        cell.textLabel.textColor = wlBlackColor;
        cell.detailTextLabel.font = [WLCommonTool fontTypePingFangSCRegular:14];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    
    cell.accessoryView = nil;
    cell.detailTextLabel.textColor = wlLightTextColor;
    cell.textLabel.text = _arrTitles[indexPath.section][indexPath.row];
    cell.detailTextLabel.text = @"";
    if (indexPath.section==0&&row==0) {
//        NSString *strType = self.dictInfo[@"static_ip"];
        NSString *strType = self.dictInfo[@"proto"];
        if ([strType isMemberOfClass:[NSNull class]]==NO) {
            if ([strType isEqualToString:@"pppoe"]) {
                cell.detailTextLabel.text = @"PPPoE";
            }
            else if ([strType isEqualToString:@"static"])
            {
                cell.detailTextLabel.text = @"静态IP";
            }
            else if ([strType isEqualToString:@"dhcp"])
            {
                cell.detailTextLabel.text = @"动态IP";
            }
        }
    }
    else if (indexPath.section==1)
    {
        if (row==1) {
            if ([self.dictInfo[@"bShareDisk"] boolValue]==false) {
                cell.detailTextLabel.textColor = wlRedColor;
                cell.detailTextLabel.text = @"未设置";
            }
            else
            {
                cell.detailTextLabel.text = @"已设置";
            }
        }
        else if (row==2)
        {
            UISwitch *btnSwitch = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 40, WLScaleX(14))];
            btnSwitch.onTintColor = wlblueColor;//wlRGBACOLOR(26, 89, 226, 0.6);
//            btnSwitch.thumbTintColor = wlblueColor;
            [btnSwitch addTarget:self action:@selector(protectWallAction:) forControlEvents:UIControlEventValueChanged];
            btnSwitch.on = _isShowBlack;
            cell.accessoryView = btnSwitch;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        else if (row==3)
        {
            if ([self.dictInfo[@"blackcount"] integerValue]>0) {
                cell.detailTextLabel.text = [NSString stringWithFormat:@"%@台设备",self.dictInfo[@"blackcount"]];
            }
            else
            {
                cell.detailTextLabel.text = @"0台设备";
            }
        }
    }
//    else if (indexPath.section==2)
//    {
//        NSString *strType = self.dictInfo[@"version"];
//        if ([strType isMemberOfClass:[NSNull class]]==NO) {
//            cell.detailTextLabel.text = strType;
//        }
//    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (indexPath.section) {
        case 0:
        {
            switch (indexPath.row) {
                case 0:
                    {
                        WLRouterInternetSetController *internetSetController = [[WLRouterInternetSetController alloc] init];
//                        internetSetController.netConfig = self.configModel;
                        internetSetController.netType = self.dictInfo[@"proto"];
                        [self.navigationController pushViewController:internetSetController animated:YES];
                    }
                    break;
                case 1:
                {
                    WLRouterWiFiSetController *wifiSetController = [[WLRouterWiFiSetController alloc] init];
//                    wifiSetController.wifiConfig = self.configModel;
                    [self.navigationController pushViewController:wifiSetController animated:YES];
                }
                    break;
                    
                default:
                    break;
            }
        }
            break;
        case 1:
        {
            switch (indexPath.row) {
                case 0:
                {
                    WLRouterDeviceManagerController *deviceManagerController = [[WLRouterDeviceManagerController alloc] init];
                    deviceManagerController.isOpenBlacks = self.isShowBlack;
                    [self.navigationController pushViewController:deviceManagerController animated:YES];
                }
                    break;
                case 1:
                {
                    WLRouterShareDiskController *shareDiskController = [[WLRouterShareDiskController alloc] init];
                    [self.navigationController pushViewController:shareDiskController animated:YES];
                }
                    break;
                case 3:
                {
                    WLRouterBlackDeviceController *blackDeviceController = [[WLRouterBlackDeviceController alloc] init];
                    [self.navigationController pushViewController:blackDeviceController animated:YES];
                }
                    break;
                    
                default:
                    break;
            }
        }
            break;
        case 2:
        {
            
        }
            break;
            
        default:
            break;
    }
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (void)protectWallAction:(UISwitch *)switchBtn
{
    _isShowBlack = switchBtn.on;
    if (switchBtn.on) {
        _arrTitles =@[@[@"联网设置",@"WiFi设置"],@[@"联网设备管理",@"共享磁盘管理",@"防火墙",@"黑名单管理"]];
    }
    else
    {
        _arrTitles =@[@[@"联网设置",@"WiFi设置"],@[@"联网设备管理",@"共享磁盘管理",@"防火墙"]];
    }
    NSDictionary *dictParamer = @{@"bOpen":@(_isShowBlack)};
    NSError *parseError;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictParamer options:NSJSONWritingPrettyPrinted error:&parseError];
    NSString *strContent = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
    NSDictionary *dict = @{@"type":@"DEVICE_BLACK_STATUS_SET",@"content":strContent};
    [[WLSocketManager sharedSocketManager] sendMessage:dict timeOut:-1 tag:0];
    [self.tbSetting reloadData];
}

- (void)showSettingMaskView
{
    CGRect frame = [UIScreen mainScreen].bounds;
    UIView *bgView = [[UIView alloc]initWithFrame:frame];
    bgView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.7];
    [self.navigationController.view addSubview:bgView];
    
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:1 inSection:1];
    CGRect rectCell = [self.tbSetting rectForRowAtIndexPath:indexPath];
    CGRect cutRect = [self.tbSetting convertRect:rectCell toView:bgView];
    
    UIBezierPath *path = [UIBezierPath bezierPathWithRect:frame];
    [path appendPath:[[UIBezierPath bezierPathWithRect:cutRect] bezierPathByReversingPath]];
    
    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    shapeLayer.path = path.CGPath;
    [bgView.layer setMask:shapeLayer];
    
    UIImage *imgArrow = [UIImage imageNamed:@"router_second_arrow"];
    UIImageView *ivArrow = [[UIImageView alloc] initWithImage:imgArrow];
    ivArrow.center = CGPointMake(WLScaleX(40)+22, CGRectGetMinY(cutRect)-WLScaleX(10)-28-17);
    [bgView addSubview:ivArrow];
//    ivArrow.image = [imgArrow rotate:UIImageOrientationLeft];
    CGAffineTransform transform= CGAffineTransformMakeRotation(M_PI);
    ivArrow.transform = transform;//旋转
    
    UIImageView *ivText = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"setting_disk_text"]];
    ivText.center = CGPointMake(WLScaleX(40)+43+2+125, CGRectGetMinY(ivArrow.frame));
    [bgView addSubview:ivText];
    
    UIButton *btnNext = [[UIButton alloc] initWithFrame:CGRectMake(CGRectGetMinX(ivText.frame), CGRectGetMaxY(ivText.frame)+WLScaleX(18), 90, 30)];
    [btnNext setBackgroundImage:[UIImage imageNamed:@"mask_next_btn"] forState:UIControlStateNormal];
    [btnNext addTarget:self action:@selector(settingFirstMaskAction:) forControlEvents:UIControlEventTouchUpInside];
    [bgView addSubview:btnNext];
}

- (void)settingFirstMaskAction:(UIButton *)btnNext
{
    UIView *bgView = btnNext.superview;
    
    NSArray *arrLayers = [NSArray arrayWithArray:bgView.layer.sublayers];
    for (CALayer *subLayer in arrLayers) {
        if ([subLayer isKindOfClass:[CAGradientLayer class]])
        {
            [subLayer removeFromSuperlayer];
        }
    }
    
    for (UIView *subView in bgView.subviews)
    {
        [subView removeFromSuperview];
    }
    
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:1 inSection:0];
    CGRect rectCell = [self.tbSetting rectForRowAtIndexPath:indexPath];
    CGRect cutRect = [self.tbSetting convertRect:rectCell toView:bgView];
    
    UIBezierPath *path = [UIBezierPath bezierPathWithRect:bgView.frame];
    [path appendPath:[[UIBezierPath bezierPathWithRect:cutRect] bezierPathByReversingPath]];
    
    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    shapeLayer.path = path.CGPath;
    [bgView.layer setMask:shapeLayer];
    
    UIImageView *ivArrow = [[UIImageView alloc] initWithFrame:CGRectMake(WLScaleX(40), CGRectGetMaxY(cutRect)+5, 43, 35)];
    ivArrow.image = [UIImage imageNamed:@"mask_arrow_ltop"];
    [bgView addSubview:ivArrow];
    
    UIImageView *ivText = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"setting_wifi_text"]];
    ivText.center = CGPointMake(CGRectGetMaxX(ivArrow.frame)+5+106, CGRectGetMaxY(ivArrow.frame));
    [bgView addSubview:ivText];
    
    UIButton *btnSecond = [[UIButton alloc] initWithFrame:CGRectMake(CGRectGetMinX(ivText.frame), CGRectGetMaxY(ivText.frame)+WLScaleX(15), 90, 30)];
    [btnSecond setBackgroundImage:[UIImage imageNamed:@"mask_next_btn"] forState:UIControlStateNormal];
    [btnSecond addTarget:self action:@selector(settingThirdMaskViewAction:) forControlEvents:UIControlEventTouchUpInside];
    [bgView addSubview:btnSecond];
}

- (void)settingThirdMaskViewAction:(UIButton *)btnNext
{
    UIView *bgView = btnNext.superview;
    
    NSArray *arrLayers = [NSArray arrayWithArray:bgView.layer.sublayers];
    for (CALayer *subLayer in arrLayers) {
        if ([subLayer isKindOfClass:[CAGradientLayer class]])
        {
            [subLayer removeFromSuperlayer];
        }
    }
    
    for (UIView *subView in bgView.subviews)
    {
        [subView removeFromSuperview];
    }
    
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:2 inSection:1];
    CGRect rectCell = [self.tbSetting rectForRowAtIndexPath:indexPath];
    CGRect cutRect = [self.tbSetting convertRect:rectCell toView:bgView];
    
    UIBezierPath *path = [UIBezierPath bezierPathWithRect:bgView.frame];
    [path appendPath:[[UIBezierPath bezierPathWithRect:cutRect] bezierPathByReversingPath]];
    
    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    shapeLayer.path = path.CGPath;
    [bgView.layer setMask:shapeLayer];
    
    UIImageView *ivArrow = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"mask_arrow_rbottom"]];
    ivArrow.center = CGPointMake(WIDTH_SCREEN_WL-16-20-5-17, CGRectGetMinY(cutRect)-WLScaleX(10)-30);
    [bgView addSubview:ivArrow];
    
    UIImageView *ivText = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"setting_black_text"]];
    ivText.center = CGPointMake(CGRectGetMinX(ivArrow.frame)-5-98, CGRectGetMinY(ivArrow.frame));
    [bgView addSubview:ivText];
    
    UIButton *btnSecond = [[UIButton alloc] initWithFrame:CGRectMake(CGRectGetMinX(ivText.frame), CGRectGetMaxY(ivText.frame)+WLScaleX(15), 90, 30)];
    [btnSecond setBackgroundImage:[UIImage imageNamed:@"mask_know_btn"] forState:UIControlStateNormal];
    [btnSecond addTarget:self action:@selector(settingMaskViewAction:) forControlEvents:UIControlEventTouchUpInside];
    [bgView addSubview:btnSecond];
}

- (void)settingMaskViewAction:(UIButton *)btnOver
{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setInteger:4 forKey:@"maskGuideIndex"];
    UIView *view = btnOver.superview;
    [view removeFromSuperview];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
